import pika
import time
import sys
import os


def main():
    auth = pika.PlainCredentials('test', 'test')

    connection = pika.BlockingConnection(
        pika.ConnectionParameters('hadoop888', credentials=auth))
    channel = connection.channel()
    channel.queue_declare(queue='task_queue', durable=True)  # durable=True

    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body.decode())
        count = body.count(b'.')
        for i in range(count):
            print("sleep 1 second of %d" % count)
            time.sleep(1)
        print(" [x] Done")
        ch.basic_ack(delivery_tag=method.delivery_tag)

    channel.basic_qos(prefetch_count=1)  # 保证 worker 不会积压太多消息
    channel.basic_consume(queue='task_queue',
                          auto_ack=False,
                          on_message_callback=callback)

    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)
